const app = getApp()

Page({
  data: {
    phoneClient: '',
    isShow: false,
    condition: true,
    open_id: '',
    unionid: '',
    user_info: '',
    phone: ''
  },


  // onUnload: function () {
  //   tt.switchTab({
  //     url: '/pages/index/index',
  //   });
  // },
  onLoad: function () {
    app.globalData.is_login = 1;
    var that = this;
    var icon = 'none'
    tt.getSystemInfo({
      success(res) {
        that.setData({
          phoneClient: res.model
        })
      },
      fail(res) {
        console.log(`获取系统信息失败`);
      }
    });
    // tt.checkSession({
    //   success(res) {
    //     console.log(`session未过期`);
    //   },
    //   fail(res) {
    //     console.log(`session已过期，需要重新登录`);
    //   }
    // });
  },

  /**
   * 登录事件
   */
  login: function () {
    var that = this;
    var code = '';
    //小程序自带登入
    tt.login({
      success(res) {
        code = res.code;
        console.log(`login调用成功` + res.code);
        //获取头条用户信息
        tt.getUserInfo({
          data: {
            withCredentials: true
          },
          success(res) {
            console.log(res.rawData);
            console.log(res);
            console.log(res.userInfo);

            tt.setStorageSync('userInfo', res.userInfo)

            app.globalData.toutiaoInfo = res.userInfo
            that.setData({
              user_info: res.userInfo
            });

            //后端获取信息
            tt.request({
              url: app.globalData.url + 'index.php?act=toutiao_login&op=index&appid=' + app.globalData.appid + '&code=' + code, // 目标服务器url,
              header: {
                "Content-Type": "application/x-www-form-urlencoded"
              },
              method: 'POST',
              dataType: 'json',
              data: {
                nickName: res.userInfo.nickName,
                avatarUrl: res.userInfo.avatarUrl,
                client: that.data.phoneClient
              },
              success: (res) => {
                if (res.data.code == 200) {
                  var open_id = res.data.datas.openid
                  that.setData({
                    unionid: res.data.datas.unionid
                  });

                  that.setData({
                    open_id: open_id
                  })

                  tt.setStorageSync('open_id', open_id)
                  tt.setStorageSync('unionid', res.data.datas.unionid)

                  if (res.data.datas.status == 1) {
                    app.globalData.open_id = res.data.datas.openid
                    app.globalData.token = res.data.datas.key


                    tt.setStorageSync('token', res.data.datas.key)

                    tt.showToast({
                      title: '登入成功',
                      icon: 'none',
                      duration: 700,
                      success(res) {
                        tt.switchTab({
                          url: '/pages/index/index'
                        })
                      },
                    });


                  } else {
                    that.setData({
                      isShow: true
                    });
                  }

                } else {
                  tt.showToast({
                    title: res.data.datas.error,
                    icon: 'none',
                    duration: 2500
                  });
                }
              },
            });
          },
          fail(res) {
            console.log(`getUserInfo调用失败`);
          }
        });
      },
      fail(res) {
        console.log(`login调用失败`);
      }
    });
  },

  /**
   * 输入手机号
   */
  inputPhone: function (e) {
    var that = this;
    that.setData({
      phone: e.detail.value
    })
  },

  /**
   * 注册
   */
  register: function () {
    var that = this;

    var isTrue = that.isPoneAvailable(that.data.phone)
    if (!isTrue) {
      tt.showToast({
        title: '请输入正确的手机号',
        icon: 'none',
        duration: 2500
      })
    } else {
      tt.request({
        url: app.globalData.url + 'index.php?act=toutiao_login&op=tt_register', // 目标服务器url,
        header: {
          "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
        },
        method: 'POST',
        dataType: 'json',
        data: {
          nickName: that.data.user_info.nickName,
          avatarUrl: that.data.user_info.avatarUrl,
          client: that.data.phoneClient,
          openid: that.data.open_id,
          unionid: that.data.unionid,
          phone: that.data.phone
        },
        success: (res) => {
          if (res.data.code == 200) {
            app.globalData.token = res.data.datas.key
            tt.setStorageSync('token', res.data.datas.key)

            tt.showToast({
              title: '登入成功',
              icon: 'none',
              duration: 700,
              success(res) {
                tt.switchTab({
                  url: '/pages/index/index'
                })
              }
            });

          } else {
            tt.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 2500
            });
          }
        },
      })
    }
  },

  /**
   * 验证手机号
   */
  isPoneAvailable: function (str) {
    var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
    if (!myreg.test(str)) {
      return false;
    } else {
      return true;
    }
  }
})
